//
//  Public.m
//  Network
//
//  Created by phq on 2019/7/4.
//  Copyright © 2018 job1001. All rights reserved.
//

#import "HPHelper.h"

#import "HPEncode.h"
#import "HPDefine.h"
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
#import "HPRequest.h"

@implementation HPHelper


// GMT date
+ (NSString *)stringFromDateGMT {
    NSDate *date = [NSDate date];
    NSTimeZone *tzGMT = [NSTimeZone timeZoneWithName:@"GMT+8"];
    [NSTimeZone setDefaultTimeZone:tzGMT];
    
    NSDateFormatter *iosDateFormater=[[NSDateFormatter alloc]init];
    iosDateFormater.dateFormat=@"EEE d MMM yyyy HH:mm:ss 'GMT'";
    iosDateFormater.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    NSString *dateString = [iosDateFormater stringFromDate:date];
    return dateString;
}


#pragma mark - 数据加解密

// 中文 unicode
+ (NSString *)unicodeEncode:(NSString*)text {
    return [text encodeUnicode];
}

// url utf8
+ (NSString *)utf8Encode:(NSString*)text {
    if (text==nil) return @"";
    return [text utf8Encode];
}
+ (NSString *)utf8Decode:(NSString*)text {
    if (text==nil) return @"";
    return [text utf8Decode];
}

// 将指定的数据进行DES加密 ，
+ (NSData*)encryptDES:(NSString*)text withKey:(NSString *)key {
    NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
    return [data des_encrypt:key];
}

// 对指定的数据进行DES解密
+ (NSData*)decryptDES:(NSData*)text withKey:(NSString *)key {
    return [text des_decrypt:key];
}

//  base64 加密
+ (NSString *)base64EncodedWithData:(NSData *)data {
    return [data base64Encode];
}
+ (NSString *)base64EncodedWithString:(NSString *)str {
    return [str base64Encode];
}
//  base64 解密
+ (NSData *)dataWithBase64EncodedString:(NSString *)string {
    return [NSData base64Decode:string];
}

// md5 加密
+ (NSString *)md5WithString:(NSString *)string {
    return [string md5Encode];
}

// sha1 算法
+ (NSString *)hmacsha1WithString:(NSString *)string withKey:(NSString *)key {
    return [string hmacsha1EncodeWithKey:key];
}


#pragma mark - 其它


// 字典转JSON字符串方法
+ (NSString *)stringWithJson:(id)dict {
    if (dict == nil) {
        return @"";
    }
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    if (!jsonData) {
        NSLog(@"-----convertToJsonData error = %@",error);
        return nil;
    }
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}
// JSON字符串转化为字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {return nil; }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"----json解析失败：%@",err);
        return nil;
    }
    return dic;
}

//获取系统可用空间大小 单位byte
+ (long long)getSystemCanUseMemoryNotUnit {
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
    
    if (dictionary)
    {
        NSNumber *_free = [dictionary objectForKey:NSFileSystemFreeSize];
        return [_free unsignedLongLongValue];
    }
    return 0;
}

// 简单的Alert（只有“确定”按钮）
+ (void)alertWithMessage:(nonnull NSString *)message
               handler:(void (^ __nullable)(UIAlertAction *action))handler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:handler];
    [alertController addAction:cancelAction];
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
    });
}

//model转NSDictionary
+ (NSDictionary *)properties_aps:(id)model {
    if (!model) {
        return nil;
    }
    NSMutableDictionary *props = [NSMutableDictionary dictionary];
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([model class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        const char* char_f =property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];
        id propertyValue = [model valueForKey:(NSString *)propertyName];
        if (propertyValue) {
            [props setObject:propertyValue forKey:propertyName];
        }
    }
    free(properties);
    return props;
}

//判断是否是纯汉字
+ (BOOL)isChinese:(NSString *)str {
    if(str.length == 0) return NO;
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:str];
}

//判断是否含有汉字
+ (BOOL)includeChinese:(NSString*)str {
    for (int i=0; i<str.length; i++) {
        unichar ch = [str characterAtIndex:i];
        if (0x4E00 <= ch  && ch <= 0x9FA5) {
            return YES;
        }
    }
    return NO;
}




@end
